package rge.orumus.encdb;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;

import rge.orumus.androidutils.SimpleCrypto;

public class EncDB {
	
	private static final String PASSWORD = "TEMPORARY PASSWORD";
	public String fileName;
	
	private EncDBHelper db;
	
	public enum RecordType{
		RECORD_UNKNOWN,
		RECORD_NOT_DECRYPTED,
		RECORD_TEXT,
		RECORD_CREDIT_CARD,
		RECORD_ONLINE_CREDENTIALS,
		RECORD_IMAGE
	}
	
	public EncDB(Context context, String fileName){
		this.fileName = fileName;
		db = new EncDBHelper(context);
	}
	
	public enum EncDBIOResult{
		OK,
		FAILURE
	}
	
	public static byte[] Decrypt(byte[] encryptedData){
		try {
			return SimpleCrypto.decrypt(PASSWORD, encryptedData);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static byte[] Encrypt(byte[] data){
		try {
			return SimpleCrypto.encrypt(PASSWORD, data);
		} catch (Exception e) {
			return null;
		}
	}
	
	public EncDBIOResult Load(){
		throw new UnsupportedOperationException("EncDB.Load()");
	}
	
	public EncDBIOResult Save(){
		return Save(fileName);
	}
	
	public EncDBIOResult Save(String toFile){
		throw new UnsupportedOperationException("EncDB.Save(String toFile)");
	}
	
	public ArrayList<RecordHeader> GetHeaders(){
		Cursor cHeaders = db.getHeaders();
		int iIndex = cHeaders.getColumnIndex("_index");
		int iTitle = cHeaders.getColumnIndex("_title");
		int iType  = cHeaders.getColumnIndex("_type");
		ArrayList<RecordHeader> res = new ArrayList<RecordHeader>();
		
		if(cHeaders.moveToFirst()){
			do{
				int index = cHeaders.getInt(iIndex);
				String title = cHeaders.getString(iTitle);
				String type = cHeaders.getString(iType);
				res.add(new RecordHeader(index, EncDB.RecordType.valueOf(type), title));
			} while(cHeaders.moveToNext());
		}
		cHeaders.close();
		return res;
	}

	public RecordData GetDataRecord(int index){
		throw new UnsupportedOperationException("EncDB.GetDataRecord(int index)");
	}

	public void updateRecord(RecordHeader rh, RecordData rd) {
		if(rh.index < 0){
			addNewRecord(rh, rd);
		}
		// TODO : add code to update existing record
	}

	private void addNewRecord(RecordHeader rh, RecordData rd) {
		db.insertRecord(rh.title, rh.type.toString(), rd.toString());
	}
}
